import * as fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'url';
import { exec } from 'node:child_process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 'shopping-cart' >> 'ShoppingCart'
function fileName2camel(fileName) {
  // 'shopping' >> 'Shopping'
  // 'cart' >> 'Cart'
  return fileName
    .split('-')
    .map((s) => {
      const firstLetter = s[0];
      return firstLetter.toUpperCase() + s.substring(1);
    })
    .join('');
}

(async () => {
  // 清空目标文件夹
  const iconComponentsUrl = path.join(__dirname, '../src/icon-components');
  const componentfiles = await fs.readdir(iconComponentsUrl);
  for (const componentFileName of componentfiles) {
    await fs.rm(path.join(iconComponentsUrl, componentFileName), { force: true });
  }
  // 读取src/icons中的文件列表
  const iconsUrl = path.join(__dirname, '../src/icons');
  const files = await fs.readdir(iconsUrl);
  let importContent = '';
  let componentContent = '';
  for (const fileName of files) {
    const iconUrl = path.join(iconsUrl, fileName);
    const fileContent = await fs.readFile(iconUrl, { encoding: 'utf8' });
    const newContent = `
      <script setup>
      defineProps({
        size: [
          String,
          Number,
        ],
        color: String,
      });
      </script>

      <template>
        ${ fileContent.replace(/width=\"\d\d\"\ height=\"\d\d\"/, ':width="size" :height="size"') }
      </template>
    `.replace('\n', '');
    const fileNameSimple = fileName.replace('.svg', '');
    const iconComponentUrl = path.join(iconComponentsUrl, `${ fileNameSimple }.vue`);
    fs.writeFile(iconComponentUrl, newContent, { encoding: 'utf8' });

    const camelFileNameSimple = fileName2camel(fileNameSimple);
    importContent += `import ${ camelFileNameSimple } from '@/icon-components/${ fileNameSimple }.vue';\n`;
    componentContent += `${ camelFileNameSimple },\n`;
  }

  const iconComponentContent = `
    <script setup>
    defineProps({
      name: String,
      size: {
        type: [
          String,
          Number,
        ],
        default: 32,
      },
    });
    </script>

    <script>
    ${ importContent }
    export default {
      components: {
        ${ componentContent }
      },
    };
    </script>

    <template>
      <component
        :is="name"
        :size="size"
      />
    </template>
  `.replace('\n', '');

  const iconComponentUrl = path.join(__dirname, '../src/components/icon/index.vue');

  await fs.writeFile(iconComponentUrl, iconComponentContent, { encoding: 'utf8' });

  exec('npm run lint');
})();
